<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 12-8-2
 * Time: 上午11:18
 * To change this template use File | Settings | File Templates.
 */
class pay extends MY_Controller
{
    public function index()
    {
        $payType = $this->input->get_post('pay_type');

        $type = config_item('pay_type');

        if (isset($type[$payType]))
        {
            $view = $payType;
            $bank = $type[$payType];
        }
        else
        {
            $view = 'wsyh';
            $bank = 'yeepay';
        }
        //var_dump($view);
        $this->load->view("pay/{$view}.php", array('bank'=>$bank, 'type' => $view, 'navigation' => 'pay'));
    }

    /**
     * 请求支付
     */
    public function request()
    {
        //呢称为0 通行证为1
        $accountType = intval( $this->input->get_post('account_type') );
        $payChannel = ($this->input->get_post('pay_channel'));//支付渠道
        $bankCode = ( trim($this->input->get_post('bank_code')) );//
        $passport = trim($this->input->get_post('passport'));
        $amount = intval($this->input->get_post('amount'));
        $ip = $this->input->ip_address();

        //测试充值代码 如果充值帐号是测试帐号`123123` 则 `充值金额/100` 测试时1元变成1分节省测试资金
        $amount = $passport == '123123' ? ($amount/100) : $amount;

        log_message('PAYLOG', "account_type={$accountType}&pay_channel={$payChannel}&bank_code={$bankCode}&passport={$passport}&amount={$amount}");

        $channel = config_item('pay_type');

        if ( empty ($payChannel) || !isset ( $channel[$payChannel] ) ) {
            $this->message('提交失败', '支付渠道不存在!');
            return ;
        }

        if ( empty ($passport) ) {
            $this->message('提交失败', '账号为空!');
            return ;
        }

        if ( !$amount ) {
            $this->message('提交失败', '金额错误!');
            return ;
        }

        //*业务代码//
        $beforeDiscount = $amount;
        //*//

        $this->load->model('user/Model_User', 'user');
        $uInfo = $this->user->getUserInfoByPassport($passport);
        if ( empty ($uInfo) ) {
            $this->message('提交失败', '充值用户不存在!');
            return ;
        }

        $data = array(
            'passport' => $passport,
            'sso_id' => $uInfo['passport_id'],
            'price' => $amount,
            'exchange_rate' => '1:100',
            'ip' => $ip,
            'pay_service' => $payChannel,
            'bank_code' => $bankCode,
            'beforediscount' => $beforeDiscount,
        );

        $this->load->model('Model_Order', 'order');
        $orderSn = $this->order->addOrder($data);

        if ( !$orderSn ) {
            $this->message('提交失败', '系统繁忙，请稍后再试');
            return ;
        }

//echo $channel[$payChannel];exit;
        $name = '围棋充值';
        $desc = '购买围棋元宝';
        $channelName = $channel[$payChannel];
        $html = '';
        switch (strtoupper($channelName)) {
            case 'ALIPAY':
                $this->load->model('pay/model_pay_alipay', 'pay');
                break;
            case 'YEEPAY':
                $this->load->model('pay/model_pay_yeepay', 'pay');
                break;
//            case 'CFT':
//                $this->load->model('pay/model_Pay_Cft', 'pay');
//                break;
            case '99BILL':
                $this->load->model('pay/model_pay_99bill', 'pay');
                break;
            case '99BILL_GAMECARD':
                $this->load->model('pay/model_pay_99bill_gamecard', 'pay');
                break;
            default:
                $this->load->model('pay/model_pay_Yeepay', 'pay');
                break;
        }

        $array = array(
            'order_sn' => $orderSn,
            'amount' => $amount,
            'name' => $name,
            'desc' => $desc,
            'bank' => $bankCode,
            'payerName' => $passport,
        );
        $html = $this->pay->request( $array );

        if (!$html || $html == '') {
            $this->message('提交失败', '下单失败，参数不全!');
            return ;
        }

        echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>请等待,连接银行中...</title></head><body>{$html}</body></html>";
    }

    /**
     * 支付回调
     */
    public function payBack()
    {
        log_message("PAYLOG", print_r($_SERVER,true)."\n".print_r($_GET,true)."\n".print_r($_POST,true)."\n\n\n");

        $response = array('error' => '0', 'msg' => '支付成功', 'code' => 'pay_success');
        $payResult = null;
        do {
            //未知的支付渠道
            $paymentChannel = $this->checkPaymentChannel();
            if (empty ($paymentChannel) || $paymentChannel == '') {
                $response = error(30019);
                break;
            }

            $this->load->helper('url');
            $this->load->model('model_order', 'order');
            $this->load->model("pay/model_pay_{$paymentChannel}", 'channel');
            $payResult = $this->channel->response();

            $order_updata = array('order_flag' => '2', 'update_time' => date('Y-m-d H:i;s'), 'back_url' => site_url('pay/payBack?').http_build_query($_REQUEST));
            //2 签名错误
            if ($payResult['status'] == 2) {
                $this->order->updateOrderByOrderSn($order_updata, $payResult['order_sn']);

                $response = error(30020);
                $response['order_sn'] = $payResult['order_sn'];
                break;
            }

            //3 订单支付失败
            if ($payResult['status'] == 3) {
                $this->order->updateOrderByOrderSn($order_updata, $payResult['order_sn']);

                $response = error(30021);
                $response['order_sn'] = $payResult['order_sn'];
                break;
            }

            //未知的订单
            $orderInfo = $this->order->getOrderByOrderSn($payResult['order_sn']);
            if (empty ($orderInfo)) {
                $response = error(30022);
                $response['order_sn'] = $payResult['order_sn'];
                break;
            }

            //支付金额有误
            if ($orderInfo['price'] != $payResult['amount']) {
                $this->order->updateOrderByOrderSn($order_updata, $payResult['order_sn']);

                $response = error(30023);
                $response['order_sn'] = $payResult['order_sn'];
                break;
            }

            //更新订单信息
            if($orderInfo['order_flag'] != '1')
            {
                $order_updata['order_flag'] = '1';
                $status = $this->order->updateOrderByOrderSn($order_updata, $payResult['order_sn']);
                if (! $status) {
                    $response = error(30024);
                    $response['order_sn'] = $payResult['order_sn'];
                    break;
                }
            }

            if($orderInfo['exchange_flag'] == '1')
            {
                $response['order_sn'] = $payResult['order_sn'];
                break;
            }

            $amount = $orderInfo['price'];
            //一卡通与神州行充值，去除手续费
            if ($orderInfo['pay_service'] == 'game_card')
            {
                $amount = intval($orderInfo['price'] * 0.85);
            }
            if ($orderInfo['pay_service'] == 'szx')
            {
                if ($orderInfo['price'] == 50)
                {
                    $amount = 47;
                } else if ($orderInfo['price'] == 100)
                {
                    $amount = 93;
                }
            }

            /**
             * 调用接口 return flag
             * 更新数据库 return flag
             */
            
            //调用游戏方接口，进行充值对换
            $sign = md5($orderInfo['passport'].$amount.$orderInfo['order_sn'].config_item('CLIENT_PAY_KEY'));
            $data = array('fillAccount'=>$orderInfo['passport'], 'trueMoney'=>$amount, 'fillOrder'=>$orderInfo['order_sn'], 'channel'=>config_item('CLIENT_PAY_MARK'), 'sign'=>$sign,);

            $gamePayStatus = @post(config_item('CLIENT_PAY_PATH'), $data);

            //$gamePayStatus = 'iReturn=0&fillAccount=zqhjerry@tom.com&trueMoney=1.00&fillOrder=201151029&sign=1F8A0D40474C96991001217C20E500F7&sMessage=充值成功';
            parse_str($gamePayStatus, $returnData);

            if($gamePayStatus === false || ($returnData['iReturn'] != '0' && $returnData['iReturn'] != '2'))
            {
                $response = error(30025);//调用接口失败
                //$response['msg'] .= '--'.$returnData['sMessage'];
                $response['order_sn'] = $payResult['order_sn'];
                break;
            }

            //$exchange_price = $orderInfo['price'];
            $updateExchangeData = array('exchange_flag' => '1', 'returnvalue' => $gamePayStatus, 'exchange_price' => $amount);
            $update_status = $this->order->updateOrderByOrderSn($updateExchangeData, $payResult['order_sn']);

            if (!$update_status) {
                $response = error(30026); //兑换失败
                $response['order_sn'] = $payResult['order_sn'];
                break;
            }

            $response['order_sn'] = $payResult['order_sn'];

            /**
             * 存放活动相关代码 -- 开始
             */
            //$this->onePayActivity($passport, $amount);

            /**
             * 存放活动相关代码 -- 结束
             */


        } while (false);

        if($payResult=== null)
        {
            show_404();
        }

        if ( $payResult['request_type'] == 2 ) {
            echo ($payResult['status'] === 1) ? $payResult['response'] : '';
        } else {
            //获取订单信息
            $orderInfo = array();
            if ( !empty ($response['order_sn']) ) {
                $this->load->model('order/Model_Order', 'order');
                $orderInfo = $this->order->getOrderByOrderSn($response['order_sn']);
            }

            $this->load->view('pay/result', array('response' => $response, 'order' => $orderInfo));
        }
    }

    /**
     * 检查支付渠道
     *
     * @return string
     */
    private function checkPaymentChannel()
    {
        $payChannel = '';

        do {
            $merchantId = $this->input->get_post('p1_MerId');
            $yeePayMerchantId = config_item('yeepay_merchant_id');
            if ( ($merchantId !== false) && ($merchantId == $yeePayMerchantId) )
            {
                $payChannel = 'yeepay';
            }

            $merchantId = $this->input->get_post('seller_id');
            $aliPayMerchantId = config_item('alipay_merchant_id');
            if ( ($merchantId !== false) && $merchantId == $aliPayMerchantId) {
                $payChannel = 'alipay';
            }


            $merchantId = $this->input->get_post('merchantAcctId');
            $kqMerchantId = config_item('99bill_merchant_id');
            if ( ($merchantId !== false) && $merchantId == $kqMerchantId) {
                $payChannel = '99bill';
            }

            $merchantId = $this->input->get_post('merchantAcctId');
            $kqMerchantId = config_item('99bill_gamecard_merchant_id');
            if (($merchantId !== false) && $merchantId == $kqMerchantId) {
                $payChannel = '99bill_gamecard';
            }

        } while (false);

        return $payChannel;
    }

    /*
     * 充值时判断用户是否激活 -- 是否在客户端登陆过
     */
    public function isActivation()
    {
        exit('1');
        $userName    = $this->_p_userName;
        $accountType = intval($this->_p_accountType);

        if (empty($userName))
        {
            exit('403');
        }
        $user = @loadMod('user.user');
        if ($accountType == 1)
        {
            $type = loadModConst('user.user.QUERY_NICKNAME');
            $data = $user->getUser($userName, $type);
            if (empty($data))
            {
                $updateNickNameStatus = $this->getClientNickName($userName);
                $data = $updateNickNameStatus ? true : false;
            }
        } else {
            $type = loadModConst('user.user.QUERY_PASSPORT');
            $data = $user->getUser($userName, $type);
        }

        exit(empty($data[0]['nickname']) ? '0' : '1');
    }

    /**
     * 充值帮助中心
     */
    public function pay_help()
    {
        $payHelpType = $this->input->get_post('pay_help_type');

        $type = config_item('pay_type');

        if (isset($type[$payHelpType])) {
            $view = $payHelpType;
            $bank = $type[$payHelpType];
        } else {
            $view = 'wsyh';
            $bank = 'yeepay';
        }
        //var_dump($view);
        $this->load->view("pay/{$view}_help.php", array('bank'=>$bank, 'type' => $view, 'navigation' => 'pay'));
    }


    /********************  充值活动代码  *********************************/

    /**
     * 第一次充值并金额超过10元  其他按充值金额区间
     *
     * @param $passport
     * @param $amount
     * @param int $count
     * @return bool
     */
    public function onePayActivity($passport, $amount, $count = 1)
    {
        if (empty($passport)) return false;

        $this->load->model('model_weiqi_user', 'user');
        //$getInfo = loadMod('interface.getinfo');
        //$type    = loadModConst('interface.getinfo.GIFTPROPS');

        /*
        if (count($payData) < 2)
        {
            $data    = $getInfo->formatData($getInfo->giftProps($passport, 7001));
        }*/

        if ($amount >= 100 && $amount <= 299)
        {
            $this->user->giftProps($passport, 10001, 2);
            $this->user->giftProps($passport, 11001, 4);
            $this->user->giftProps($passport, 4001, 4);
            //$data = $getInfo->formatData($getInfo->giftProps($passport, 7001, 2));
        } else if($amount >= 300 && $amount <= 499)
        {
            $this->user->giftProps($passport, 10001, 6);
            $this->user->giftProps($passport, 11001, 12);
            $this->user->giftProps($passport, 4002, 4);
            //$data    = $getInfo->formatData($getInfo->giftProps($passport, 7001, 7));
        } else if ($amount >= 500 && $amount <= 999)
        {
            $this->user->giftProps($passport, 10002, 5);
            $this->user->giftProps($passport, 11002, 10);
            $this->user->giftProps($passport, 4003, 4);
            //$data    = $getInfo->formatData($getInfo->giftProps($passport, 7001, 15));
        } else if ($amount >= 1000 && $amount <= 1999)
        {
            $this->user->giftProps($passport, 10002, 10);
            $this->user->giftProps($passport, 11002, 20);
            $this->user->giftProps($passport, 4004, 4);
            //$data    = $getInfo->formatData($getInfo->giftProps($passport, 7002, 15));
        }else if ($amount >= 2000 && $amount <= 4999)
        {
            $this->user->giftProps($passport, 10003, 10);
            $this->user->giftProps($passport, 11003, 20);
            $this->user->giftProps($passport, 4005, 6);
            //$data = $getInfo->formatData($getInfo->giftProps($passport, 7004, 10));
        }else if ($amount >= 5000)
        {
            $this->user->giftProps($passport, 10003, 25);
            $this->user->giftProps($passport, 11003, 30);
            $this->user->giftProps($passport, 4005, 15);
            //$data = $getInfo->formatData($getInfo->giftProps($passport, 7004, 10));
        }
    }
}
